package com.community.web.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.common.exception.NeusoftException;
import com.community.common.result.ResultCodeEnum;
import com.community.model.entity.Charge;
import com.community.model.entity.PortalWalletLog;
import com.community.model.entity.Wallet;
import com.community.web.user.mapper.WalletMapper;
import com.community.web.user.service.ChargeService;
import com.community.web.user.mapper.ChargeMapper;
import com.community.web.user.service.PortalWalletLogService;
import com.community.web.user.service.WalletService;
import com.community.web.user.vo.ChargeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
* @author admin
* @description 针对表【charge】的数据库操作Service实现
* @createDate 2024-07-02 10:56:56
*/
@Service
public class ChargeServiceImpl extends ServiceImpl<ChargeMapper, Charge>
    implements ChargeService{

    @Autowired
    private WalletService walletService;

    @Autowired
    private PortalWalletLogService logService;

    @Autowired
    private ChargeMapper mapper;

    @Autowired
    private WalletMapper walletMapper;

    @Override
    public List<ChargeVo> selectList(Long userId) {
        return mapper.getList(userId);
    }

    @Transactional
    @Override
    public void payment(Long userId, List<Long> idList) {
        //计算总价,判断余额是否足够
        BigDecimal sum = mapper.sum(userId, idList);
        Wallet wallet = walletMapper.getByUserId(userId);
        if (wallet.getWalletBalance().compareTo(sum) < 0){
            throw new NeusoftException(ResultCodeEnum.NOT_ENOUGH);
        }
        wallet.setWalletBalance(wallet.getWalletBalance().subtract(sum));
        walletService.saveOrUpdate(wallet);

        PortalWalletLog walletLog = new PortalWalletLog();
        walletLog.setWalletId(wallet.getId());
        walletLog.setAmount(sum);
        walletLog.setType(6);
        walletLog.setState(1);
        logService.addLog(walletLog);

        //修改缴纳状态
        for (Long id :
                idList) {
            LambdaUpdateWrapper<Charge> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Charge::getChargeStatus, 1);
            updateWrapper.eq(Charge::getId, id);
            super.update(updateWrapper);
        }
    }
}




